package com.zhang.sql;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @title:
 * @author: zhang
 * @date: 2022/2/13 19:54
 */
public class StreamToTableEventTime {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<Tuple3<String, String, Long>> streamOperator = env
                .readTextFile("src/main/resources/OrderLog.csv")
                .map(new MapFunction<String, Tuple3<String, String, Long>>() {
                    @Override
                    public Tuple3<String, String, Long> map(String value) throws Exception {
                        String[] fields = value.split(",");
                        return Tuple3.of(
                                fields[0],
                                fields[1],
                                Long.parseLong(fields[3]) * 1000L
                        );
                    }
                }).assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple3<String, String, Long>>forMonotonousTimestamps()
                                .withTimestampAssigner(
                                        new SerializableTimestampAssigner<Tuple3<String, String, Long>>() {
                                            @Override
                                            public long extractTimestamp(Tuple3<String, String, Long> element, long recordTimestamp) {
                                                return element.f2;
                                            }
                                        }
                                )
                );

        Table table = tableEnv.fromDataStream(streamOperator,
                $("userId"),
                $("type"),
                $("ts"),
                $("rt").rowtime());  //处理时间

        Table select = table.select(
                $("userId"),
                $("type"),
                $("ts"),
                $("rt"));

        tableEnv.toAppendStream(select, Row.class).print();

        //table.printSchema();

        env.execute();


    }
}
